import {ChangeDetectorRef, Component, ViewChild} from '@angular/core';
import {IonicPage, NavController, NavParams, Select, ToastController} from 'ionic-angular';
import {TalentPoolProvider} from "../../../providers/add-staff/talent-pool/talent-pool";
import {InfiniteScrollModel} from "../../../model/common/infinite-scroll.model";
import {PageInfoModel} from "../../../model/common/page-info.model";
import {EndlessListComponent} from "../../../components/common/endless-list/endless-list";
import {CallNumberService} from "../../../services/native/call-number/call-number.service";
import {CallNumber} from "@ionic-native/call-number";
import {ClientNoteEditProvider} from "../../../providers/client/client-note/client-note-edit/client-note-edit.provider";
import {MessageBushService} from "../../../services/common/message-bush.service";
import {LoadingService} from "../../../services/common/loading.service";
import * as moment from 'moment';
import {AdpActionSheetController} from "../../../components/common/adp-action-sheet/adp-action-sheet-controller";

declare let $;

@IonicPage()
@Component({
    selector: 'page-talent-pool',
    templateUrl: 'talent-pool.html',
    providers: [
        CallNumber,
        CallNumberService,
        ClientNoteEditProvider,
        TalentPoolProvider
    ]
})
export class TalentPoolPage extends InfiniteScrollModel {

    isLoaded = false;
    talentList;
    currentScreenData;
    listStyle: any;
    @ViewChild('endlessList') endlessList: EndlessListComponent;
    @ViewChild('phoneSelector') phoneSelector: Select;
    filterMenues = [
        {
            id: 0,
            names: [
                '姓名'
            ],
            className: "name",
            sortWay: 1,  // 0 无排序， 1 升序， 2 降序
            effective: true
        },
        {
            id: 1,
            names: [
                '名单',
                '来源'
            ],
            sortWay: 0,
            effective: false
        },
        {
            id: 2,
            names: [
                '建档',
                '日期'
            ],
            className: "createTime",
            sortWay: 0,  // 0 无排序， 1 升序， 2 降序
            effective: true
        },
        {
            id: 3,
            names: [
                '增员',
                '进度'
            ],
            sortWay: 0,
            effective: false
        },
        {
            id: 4,
            names: [
                '操作'
            ],
            className: "operator",
            sortWay: 0,
            effective: false
        }
    ];
    currentCallClient;
    keyword: string;
    params: any = {};
    processes = [];
    currentProcess = {
        id: null,
        title: ''
    };
    isiPhoneX = false;

    constructor(public navCtrl: NavController,
                public provider: TalentPoolProvider,
                public ref: ChangeDetectorRef,
                public toastCtrl: ToastController,
                public callNumberService: CallNumberService,
                public changeRef: ChangeDetectorRef,
                private load: LoadingService,
                public adpActionSheetController: AdpActionSheetController,
                public navParams: NavParams) {
        super();
        this.listStyle = {};
        this.processes = this.provider.processes;
    }

    ionViewDidLoad() {
        this.isiPhoneX = /iphone/gi.test(navigator.userAgent) && (screen.height == 812 && screen.width == 375);
        this.paramsInit();
        MessageBushService.setMessage(MessageBushService.keys.addStuffSaveSuccess, "");
        this.loadData(true);
        this.layoutInit();
    }

    paramsInit() {
        //统计开始时间
        this.params.processStartTime = this.navParams.get('processStartTime');
        if (this.params.processStartTime) {
            this.params.processStartTime = new Date(this.params.processStartTime);
            this.pageParams.condition.processStartTime = moment(new Date(moment(this.params.processStartTime).year(), moment(this.params.processStartTime).month(), moment(this.params.processStartTime).date())).unix();
        }
        //统计结束时间
        this.params.processEndTime = this.navParams.get('processEndTime');
        if (this.params.processEndTime) {
            this.params.processEndTime = new Date(this.params.processEndTime);
            this.pageParams.condition.processEndTime = moment(this.params.processEndTime).endOf('month').unix();
        }
        //跟踪进度
        this.params.process = this.navParams.get('process');
        if (this.params.process || this.params.process == 0) {
            this.pageParams.condition.process = this.params.process;
        }
        let currentProcessIndex = this.params.process ? Number(this.params.process) : 0;
        this.currentProcess = this.processes[currentProcessIndex];
    }

    ionViewDidEnter() {
        this.isLoaded = false;
        //筛选条件选择后回到当前页，使用筛选条件筛选数据
        let condition = MessageBushService.getMessage(MessageBushService.keys.talentFilterCondition);
        if (condition) {

            //region 准备请求参数
            this.pageParams.pageNum = 1;
            let conObj = JSON.parse(condition);
            this.pageParams.condition = {
                keyword: this.keyword ? this.keyword.trim() : void 0
            };

            //建档时间
            if (conObj.starttime) {
                let starttime = this.params.startTime = new Date(conObj.starttime);
                this.pageParams.condition.starttime = moment(new Date(moment(new Date(starttime)).year(), moment(new Date(starttime)).month(), moment(new Date(starttime)).date())).unix();
            } else {
                this.params.startTime = null;
                this.pageParams.condition.starttime = null;
            }
            if (conObj.endtime) {
                let endtime = this.params.endTime = new Date(conObj.endtime);
                this.pageParams.condition.endtime = moment(new Date(moment(new Date(endtime)).year(), moment(new Date(endtime)).month(), moment(new Date(endtime)).date())).unix() + 23 * 60 * 60 + 59 * 60 + 59;
            } else {
                this.params.endTime = null;
                this.pageParams.condition.endtime = null;
            }

            //跟进进度
            if (conObj.process && conObj.process.length) {

                let processIndexes = [];
                conObj.process.forEach((i, index) => {
                    if (i.selected) {
                        processIndexes.push(index);
                    }
                });
                if (processIndexes.length === 1) {
                    this.currentProcess = this.processes[processIndexes[0]];
                } else {
                    this.currentProcess = {
                        id: -1,
                        title: "人才库"
                    };
                }

                this.pageParams.condition.process = this.params.process = processIndexes.join(',');
            } else {
                this.currentProcess = {
                    id: -1,
                    title: "人才库"
                };
                this.pageParams.condition.process = null;
            }

            //来源
            if (conObj.origins && conObj.origins.length) {
                let originsSelected = conObj.origins.filter(i => i.selected).map(i => i.title);
                this.pageParams.condition.source = originsSelected.join(',');
            } else {
                this.pageParams.condition.source = null;
            }

            //统计时间
            if (conObj.processStartTime) {
                let o = this.params.processStartTime = new Date(conObj.processStartTime);
                this.pageParams.condition.processStartTime = moment(new Date(moment(new Date(o)).year(), moment(new Date(o)).month(), moment(new Date(o)).date())).unix();
            } else {
                this.params.processStartTime = null;
                this.pageParams.condition.processStartTime = null;
            }
            if (conObj.processEndTime) {
                let o = this.params.processEndTime = new Date(conObj.processEndTime);
                this.pageParams.condition.processEndTime = moment(o).endOf('month').unix();
            } else {
                this.params.processEndTime = null;
                this.pageParams.condition.processEndTime = null;
            }

            //endregion

            this.provider.getDataByPage(this.pageParams, this.load).subscribe(pageData => {
                this.pageInfo = pageData as PageInfoModel;
                this.talentList = this.pageInfo.list;
                this.currentScreenData = this.pageInfo.list;
                this.isLoaded = true;
                this.endlessList.isArriveBottom = false;
            });
            this.isLoaded = true;
            MessageBushService.setMessage(MessageBushService.keys.talentFilterCondition, '');
        }

        //编辑并保存增员信息后回到当前页
        let needUpdate = MessageBushService.getMessage(MessageBushService.keys.addStuffSaveSuccess);
        if (needUpdate) {
            this.pageParams.pageNum = 1;
            this.loadData();
            MessageBushService.setMessage(MessageBushService.keys.addStuffSaveSuccess, "");
        }
    }

    searchKeyUp(e) {
        if ('Enter' === e.key || 13 === e.keyCode) {
            this.searchClickHandle();
        }
    }

    listGoup() {
        const self = this;
        setTimeout(() => {
            self.endlessList.isArriveBottom = false;
            self.endlessList.goUp();
        }, 200);
    }

    //搜索图标按钮单击
    searchClickHandle() {
        this.pageParams.pageNum = 1;
        if (this.keyword) {
            this.pageParams.condition.keyword = this.keyword.trim();
        } else {
            this.pageParams.condition.keyword = void 0;
        }
        this.provider.getDataByPage(this.pageParams, this.load).subscribe(pageData => {
            this.pageInfo = pageData as PageInfoModel;
            this.talentList = this.pageInfo.list;
            this.currentScreenData = this.pageInfo.list;
            this.isLoaded = true;
            this.listGoup();
        });

    }

    /**
     * 返回上一页
     */
    backToLastPage() {
        let pageParams = this.navParams.get('pageParams');
        if (pageParams) {
            this.navCtrl.push('TeamTeamIncreasePage', {overView: '0', isLoading: 1});
        } else {
            this.navCtrl.pop(null);
        }
    }

    loadData(pageLoaded = false) {
        if (pageLoaded) {
            this.pageParams.pageSize = 10;
            this.pageParams.pageNum = 1;
            this.pageParams.orderName = 'name';
            this.pageParams.orderType = 'a';
        }
        this.provider.getDataByPage(this.pageParams, this.load).subscribe(pageData => {
            this.isLoaded = true;
            this.pageInfo = pageData as PageInfoModel;
            this.talentList = this.pageInfo.list;
            this.currentScreenData = this.pageInfo.list;
            this.setNameLengthOver(this.currentScreenData);
            this.endlessList.isArriveBottom = false;
        });
    }

    vw(v: number) {
        return window.innerWidth * v / 100;
    }

    layoutInit() {
        let listHeight = window.innerHeight - this.vw(17.6) - this.vw(36.389) - this.vw(13.89);
        if (this.isiPhoneX) {
            listHeight = 511
        }
        this.listStyle.height = `${listHeight}px`;
    }

    goDetail(recruit) {
        this.navCtrl.push('AddStaffDetailPage', {
            recruit
        });
    }

    goAddIncrease() {
        if (this.params.process == undefined) {
            this.navCtrl.push('AddNewStaffPage', {'pageParams': 'pool'});
            console.log('pushPool')
        } else {
            this.navCtrl.push('AddNewStaffPage');
        }

    }

    filterClicked() {
        this.navCtrl.push('TalentFilterPage', {
            source: this.pageParams.condition.source,
            processStartTime: this.params.processStartTime,
            processEndTime: this.params.processEndTime,
            starttime: this.params.startTime,
            endtime: this.params.endTime,
            process: this.pageParams.condition.process + ''
        });
    }

    processMap(process) {
        let des = this.provider.processes[process];
        return des.title;
    }

    sourceMap(source) {
        if (source === 'msl')
            return "系统导入";
        return source;
    }

    getStrLen(str) {
        const l = str.length;
        let blen = 0;
        for (let i = 0; i < l; i++) {
            if ((str.charCodeAt(i) & 0xff00) != 0) {
                blen++;
            }
            blen++;
        }
        return blen;
    }
    setNameLengthOver(list){
        if(list && list.length){
            list.forEach(item => {
                const nameLen = this.getStrLen(item.name);
                if(nameLen / 2 > 7){
                    item.nameOverflow = true;
                }
            });
        }
    }
    getCurrentScreenData() {
        this.currentScreenData = this.currentScreenData.concat(this.pageInfo.list);
        this.setNameLengthOver(this.currentScreenData);
    }

    scrollToBottom() {
        if (this.pageParams.pageNum >= this.pageInfo.pages) {
            return;
        }
        this.endlessList.isLoadingData = true;
        this.pageParams.pageNum++;
        this.provider.getDataByPage(this.pageParams, null).subscribe(pageData => {
            this.pageInfo = pageData as PageInfoModel;
            this.talentList = this.talentList.concat(this.pageInfo.list);
            this.getCurrentScreenData();
            this.endlessList.isLoadingData = false;
            this.endlessList.isArriveBottom = false;
        });

    }

    prevSelectedMenu;

    menuClick(data) {

        if (data.effective) {

            if (this.prevSelectedMenu) {
                if (this.prevSelectedMenu.id != data.id) {
                    this.prevSelectedMenu.sortWay = 0;
                }
            } else {
                this.filterMenues[0].sortWay = 0;
            }

            if (!data.sortWay) {
                data.sortWay = 1;
                if (data.className === "createTime") {
                    data.sortWay = 2;
                }
            }

            this.pageParams.pageNum = 1;
            this.pageParams.orderName = data.className;
            this.pageParams.orderType = data.sortWay === 1 ? 'a' : 'd';
            this.provider.getDataByPage(this.pageParams, this.load).subscribe(pageData => {
                this.pageInfo = pageData as PageInfoModel;
                this.talentList = this.pageInfo.list;
                this.currentScreenData = this.pageInfo.list;
                this.listGoup();
            });

            this.prevSelectedMenu = data;
        }

    }

    callPhone(data) {

        if (data.recruitId) {
            this.currentCallClient = data;
        }

        if (data.mobileList) {
            if (data.mobileList.length === 1) {
                let phoneNum = data.mobileList[0];

                this.callNumberService.makeCall(phoneNum, {
                        noteType: 4,
                        content: "拨打电话",
                        contentType: 1,
                        clientNumber: data.recruitId,
                        clientType: 3,
                        voiceUrl: "",
                        voiceLength: ""
                    },
                    false
                );
            } else if (data.mobileList.length > 1) {

                const phoneArray = [];
                this.currentCallClient.mobileList.forEach(phone => {
                    phoneArray.push({
                        text: phone,
                        handler: () => {
                            this.callPhone({mobileList: [phone]});
                        }
                    });
                });
                this.adpActionSheetController.create({
                    title: "选择电话",
                    buttons: phoneArray
                }).present();

            } else {
                this.toastCtrl.create({
                    message: '无客户电话！',
                    position: 'middle',
                    duration: 1200
                }).present();
            }
        }
    }


}
